﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using FileManagement;
using Component;

public partial class File : System.Web.UI.Page
{
    protected string idtxt = "";
    protected string idimg = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            this.lbMsg.Text = "";
            UsersInfo us = Sessions.CurrentUser;
            if (us != null)
            {
                idtxt = Component.ConvertType.ToString(QueryHelper.GetQueryString(Request,ConstString._id));
                idimg = Component.ConvertType.ToString(QueryHelper.GetQueryString(Request, ConstString._idimg));
                string imgBig = Component.ConvertType.ToString(QueryHelper.GetQueryString(Request, ConstString._ImgBig));
                string imgSmall = Component.ConvertType.ToString(QueryHelper.GetQueryString(Request, ConstString._ImgSmall));
                if (imgSmall == "1")
                {
                    this.txtCurrentPath.Text = "/ProductSmallImg/"; 
                }
                else
                {
                    if (imgBig == "1")
                    {
                        this.txtCurrentPath.Text = "/ProductBigImg/";
                    }
                    else
                        if (!Page.IsPostBack)
                        {
                            ShowAllFile(txtCurrentPath.Text);
                            ShowAllFolder(txtCurrentPath.Text);
                        }
                }

                
            }
            else
            {
                Response.Write("Vui lòng đăng nhập");
                this.txtCurrentPath.Visible = false;
                this.FileUpload.Visible = false;
                this.imgBtUploadFile.Visible = false;
                this.cbOverWrite.Visible = false;
                this.imgBtFolderUp.Visible = false;
                this.txtNewDirectory.Visible = false;
                this.imgBtAddNewDir.Visible = false;
                this.TreeView1.Visible = false;
            }
        }
        catch //neu chua dang nhap chi cha cho xuat hien cai gi ca
        {
            Response.Write("Vui lòng đăng nhập");
            this.txtCurrentPath.Visible = false;
            this.FileUpload.Visible = false;
            this.imgBtUploadFile.Visible = false;
            this.cbOverWrite.Visible = false;
            this.imgBtFolderUp.Visible = false;
            this.txtNewDirectory.Visible = false;
            this.imgBtAddNewDir.Visible = false;
            this.TreeView1.Visible = false;
        }
    }

    //Hien thi tat ca cac thu muc len datalist
    private void ShowAllFolder(string pathCurrent)
    {
        this.TreeView1.Nodes.Clear();
        GetFolder();
        this.TreeView1.DataBind();
    }
    //Hien thi tat ca cac file
    private void ShowAllFile(string pathCurrent)
    {
        ArrayList arr = new ArrayList();
        string path = Server.MapPath("../FileUpload" + pathCurrent);
        DirectoryInfo di = new DirectoryInfo(path);
        foreach (FileInfo fi in di.GetFiles())
        {
            arr.Add(new FileManagement.CFileInfo(fi.Name, fi.Extension.Remove(0, 1), pathCurrent.Replace("//", "/") + fi.Name, this.GetSize(fi.Length), fi.LastWriteTime.ToString()));
        }
        dtlFile.DataSource = arr;
        dtlFile.DataBind();
    }
    private string GetSize(long size)
    {
        long s = 1024;
        if (size <= s)
        {
            return size.ToString() + " Bytes";
        }
        if (size < s * s && size > 1024)
        {
            return (size / s).ToString() + " KB";
        }
        else
            return Math.Round((double)(size / (s * s)), 2).ToString() + " MB";
    }
    // ShowFolder

    private void GetFolder()
    {
        string path = Server.MapPath(@"../FileUpload\");//show cac folder con
        DirectoryInfo di = new DirectoryInfo(path);
        foreach (DirectoryInfo dir in di.GetDirectories())
        {
            TreeNode node = new TreeNode();
            node.Text = dir.Name;
            string temp = path + dir.Name + "\\";
            node.Value = this.ReplacePath(path) + dir.Name + "/";
            DirectoryInfo di2 = new DirectoryInfo(temp);
            if (di2.GetDirectories().Length > 0)
            {
                node.SelectAction = TreeNodeSelectAction.Select;
                this.GetManyNode(node, temp);
            }
            this.TreeView1.Nodes.Add(node);
        }
    }
    protected void GetManyNode(TreeNode node, string path)
    {
        try
        {
            DirectoryInfo di2 = new DirectoryInfo(path);
            foreach (DirectoryInfo dir2 in di2.GetDirectories())
            {
                TreeNode n = new TreeNode();
                n.Text = dir2.Name;
                n.Value = node.Value + dir2.Name + "/";
                string temp = path + dir2.Name + "\\";
                //n.NavigateUrl = "File.aspx?Path=" + this.ReplacePath(n.Value);
                DirectoryInfo dir3 = new DirectoryInfo(temp);
                if (dir3.GetDirectories().Length > 0)
                {
                    n.SelectAction = TreeNodeSelectAction.Select;
                    this.GetManyNode(n, temp);
                }
                node.ChildNodes.Add(n);
            }
        }
        catch { }
    }


    //ham cat chuoi
    public string Substring(string input)
    {
        if (input.Trim().Length > 10)
            return input.Substring(0, 10) + "...";
        return input.Trim();
    }

    //click chuoi vao folder
    protected void lbtFolder_Click(object sender, EventArgs e)
    {
        try
        {
            lbMsg.Text = "";
            LinkButton lbt = (LinkButton)sender;
            string path = lbt.CommandArgument;
            txtCurrentPath.Text += "/" + path;
            txtCurrentPath.Text = txtCurrentPath.Text.Replace("//", "/");
            ShowAllFolder(txtCurrentPath.Text + "/");
            ShowAllFile(txtCurrentPath.Text + "/");
        }
        catch { }
    }
    //upload file len server
    private void UploadFile()
    {
        try
        {
            bool check = true;
            //file can upload den duong dan nay
            string path = Server.MapPath("../FileUpload/" + txtCurrentPath.Text + "/");
            FileInfo fi = new FileInfo(path + "\\" + FileUpload.FileName);
            string fileType = fi.Extension.Remove(0, 1);
            if (check)
            {
                if (cbOverWrite.Checked != true)//neu khong chon nut ghi de
                {
                    if (!fi.Exists)
                    {
                        FileUpload.SaveAs(path + FileUpload.FileName.Replace(" ", "_"));
                        lbMsg.Text =Component.CErrorProvider.SetMessage("Thực hiện thành công", true);
                    }
                    else
                    {
                        lbMsg.Text = Component.CErrorProvider.SetMessage("Tập tin này đã tồn tại", false);
                    }
                }
                else//neu chon nut ghi de
                {

                    FileUpload.SaveAs(path + FileUpload.FileName.Replace(" ", "_"));
                    lbMsg.Text = Component.CErrorProvider.SetMessage("Thực hiện thành công", true);
                }
            }
            else
            {
                lbMsg.Text = Component.CErrorProvider.SetMessage("Thư mục lưu file không hợp lệ", false);
            }
        }
        catch (Exception ex)
        {
            lbMsg.Text = Component.CErrorProvider.SetMessage("Kiểm tra lại:<br>" + ex.Message, false);
        }
    }

    private void DeleteFile(string path)
    {
        try
        {
            string ss = Server.MapPath("../FileUpload" + path);
            FileInfo fi = new FileInfo(ss);
            fi.Delete();
            this.ShowAllFile(this.txtCurrentPath.Text);
            lbMsg.Text = "Delete success full !";
        }
        catch
        {
            lbMsg.Text = "Can not delete this file, another application is use !";
            return;
        }
    }

    //quay lai thu muc truoc
    protected void imgBtFolderUp_Click(object sender, ImageClickEventArgs e)
    {
        //xoa tu "/" cuoi cung cho den het 
        try
        {
            lbMsg.Text = "";
            if (txtCurrentPath.Text.Trim().Length > 1)
                txtCurrentPath.Text = txtCurrentPath.Text.Remove(txtCurrentPath.Text.LastIndexOf("/"), txtCurrentPath.Text.Length - txtCurrentPath.Text.LastIndexOf("/"));
            if (txtCurrentPath.Text.Trim().Length == 0)
                txtCurrentPath.Text = "/";
            ShowAllFolder(txtCurrentPath.Text);
            ShowAllFile(txtCurrentPath.Text + "/");
        }
        catch { }
    }

    //tao thu muc
    protected void imgBtAddNewDir_Click(object sender, ImageClickEventArgs e)
    {
        lbMsg.Text = "";
        try
        {
            string path = Server.MapPath("../FileUpload/" + txtCurrentPath.Text.Trim());
            if (!Directory.Exists(path + "\\" + txtNewDirectory.Text))
            {
                Directory.CreateDirectory(path + "\\" + txtNewDirectory.Text.Replace(" ", "_"));
                lbMsg.ForeColor = System.Drawing.Color.ForestGreen;
                lbMsg.Text = Component.CErrorProvider.SetMessage("Thực hiện thành công", true);
                ShowAllFolder(txtCurrentPath.Text + "/");
                ShowAllFile(txtCurrentPath.Text + "/");
                lbMsg.Text = "";
                txtNewDirectory.Text = "";
            }
            else
                lbMsg.Text = Component.CErrorProvider.SetMessage("Thư mục này đã tồn tại", false);
        }
        catch (Exception ex)
        {
            lbMsg.Text = Component.CErrorProvider.SetMessage("Kiểm tra lại:<br>" + ex.Message, false);
        }
    }

    //click vao upload
    protected void imgBtUploadFile_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            lbMsg.Text = "";
            int s = this.FileUpload.PostedFile.ContentLength;
            UploadFile();
            ShowAllFile(txtCurrentPath.Text + "/");
            //}
        }
        catch { }
    }
    protected void dtlFile_DeleteCommand(object source, DataListCommandEventArgs e)
    {
        this.DeleteFile(e.CommandArgument.ToString());
    }
    protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
    {
        string temp = this.TreeView1.SelectedNode.Value;
        this.txtCurrentPath.Text = temp.Replace("\\", "/");
        //this.ShowAllFile(Request.Params["Path"]);
        this.ShowAllFile(this.txtCurrentPath.Text);
    }
    protected string ReplacePath(string path)
    {
        path = path.Remove(0, path.IndexOf("FileUpload"));
        path = path.Replace("FileUpload\\", "");
        path = path.Replace(@"\", "/");
        return "/" + path;
    }
}
